package au.com.handsunited.web.validator.user;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import au.com.handsunited.model.User;
import au.com.handsunited.model.validators.entity.UserValidator;
import au.com.handsunited.service.UserService;
import au.com.handsunited.web.command.user.UserEditProfileCommand;


/**
 * @author arunda
 *
 */
public class UserEditProfileValidator implements Validator {

	private static Logger logger = LoggerFactory.getLogger(UserEditProfileValidator.class);

	private final UserService userService;
	private final UserValidator userValidator;

	/**
	 *
	 */
	public UserEditProfileValidator(UserService userService, UserValidator userValidator) {
		this.userService = userService;
		this.userValidator = userValidator;
	}


	/**
	 * @see org.springframework.validation.Validator#supports(java.lang.Class)
	 */
	@Override
	public boolean supports(Class clazz) {

		return clazz.isAssignableFrom(UserEditProfileCommand.class);
	}


	/**
	 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
	 */
	@Override
	public void validate(Object target, Errors errors) {
		UserEditProfileCommand userEditProfileCommand = (UserEditProfileCommand) target;
		User user = userEditProfileCommand.getUser();

		try {
			errors.pushNestedPath("user");
			ValidationUtils.invokeValidator(userValidator, user, errors);
		} finally {
			errors.popNestedPath();
		}

		User u = userService.findUserByUsername(user.getUsername());
		if (u != null && !user.getId().equals(u.getId())) {
			errors.rejectValue("user.username", "username.exists", "Username exists.");
		}

	}
}
